package com.five.welcome.controller;

import com.five.welcome.entity.DeviceInfo;
import com.five.welcome.result.Result;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.UnknownHostException;

/**
 * @author Ywt
 */
@Tag(name = "获取设备信息")
@CrossOrigin
@RestController
@RequestMapping("/device")
public class DeviceInfoController {

    @GetMapping("/getDeviceInfo")
    public Result getDeviceInfo() throws Exception {
        InetAddress ia = null;
        String hostName = "", hostAddress = "";
        try {
            ia=ia.getLocalHost();
            hostName = ia.getHostName();
            hostAddress = ia.getHostAddress();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }

        String macAddress = getMACAddress(ia);
        DeviceInfo deviceInfo = new DeviceInfo(hostName, hostAddress, macAddress);
        return Result.ok(deviceInfo);
    }

    // 获取MAC地址的方法
    private static String getMACAddress(InetAddress ia) throws Exception {
        // 获得网络接口对象（即网卡），并得到mac地址，mac地址存在于一个byte数组中。
        byte[] mac = NetworkInterface.getByInetAddress(ia).getHardwareAddress();
        // 下面代码是把mac地址拼装成String
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < mac.length; i++) {
            if (i != 0) {
                sb.append("-");
            }
            // mac[i] & 0xFF 是为了把byte转化为正整数
            String s = Integer.toHexString(mac[i] & 0xFF);
            // System.out.println("--------------");
            // System.err.println(s);
            sb.append(s.length() == 1 ? 0 + s : s);
        }
        // 把字符串所有小写字母改为大写成为正规的mac地址并返回
        return sb.toString().toUpperCase();
    }
}
